package com.jinxin.phonecloudmusic.myapplication.activity.mainactivity;

import android.content.Intent;
import android.os.Bundle;
import android.support.percent.PercentRelativeLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.jinxin.phonecloudmusic.myapplication.R;
import com.jinxin.phonecloudmusic.myapplication.base.BaseActivity;
import com.jinxin.phonecloudmusic.myapplication.entity.GroupBean.BillboardList;
import com.jinxin.phonecloudmusic.myapplication.entity.MusicBean.Song;
import com.jinxin.phonecloudmusic.myapplication.entity.MusicBean.SongList;
import com.jinxin.phonecloudmusic.myapplication.event.MusicControlEvent;
import com.jinxin.phonecloudmusic.myapplication.fragment.dialogfragment.PlayInterfaceFragment;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.MusicCollectFragment;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.MusicDownLoadFragment;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.MusicListFragment;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.MusicMainFragment;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.MusicRecentPlayFragment;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.MusicSearchFragment;
import com.jinxin.phonecloudmusic.myapplication.fragment.fra.MusicSearchHistoryFragment;
import com.jinxin.phonecloudmusic.myapplication.presenter.IPresenter.IMainPagePresenter;
import com.jinxin.phonecloudmusic.myapplication.presenter.PresenterImpl.IMainPagePresentImp;
import com.jinxin.phonecloudmusic.myapplication.service.CloudMusicService;
import com.jinxin.phonecloudmusic.myapplication.utils.FragmentUtil;
import com.jinxin.phonecloudmusic.myapplication.utils.RxBus;
import com.jinxin.phonecloudmusic.myapplication.view.FloatView;
import com.jinxin.phonecloudmusic.myapplication.view.IMainPageView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

public class MusicMainActivity extends BaseActivity implements IMainPageView{
    @BindView(R.id.rl_play_current)
    PercentRelativeLayout rlPlayCurrent;

    private IMainPagePresenter iMainPagePresenter;
    int[] type = new int[]{1, 2, 21, 22, 24, 25};

    //歌曲中转站
    private List<SongList> hotSongs;
    private List<SongList> allHotSongs;
    private List<SongList> newSongs;
    private List<SongList> allNewSongs;
    private List<SongList> classicalSongs;
    private List<SongList> allClassicalSongs;
    private List<SongList> westernSongs;
    private List<SongList> allWesternSongs;
    private List<SongList> teleplaySongs;
    private List<SongList> allTeleplaySongs;
    private List<SongList> networkSongs;
    private List<SongList> allNetworkSongs;

    private WindowManager windowManager = null;
    private WindowManager.LayoutParams windowManagerParams = null;
    private FloatView floatView = null;

    private List<SongList> allSongs;
    private List<Song> singers=new ArrayList<>();
    private Map<String,List<SongList>> map;
    private int pos;
    private boolean bList=false;

    private PlayInterfaceFragment playInterfaceFragment;


    //由MusicMainActivity统一管理的碎片
    private MusicMainFragment musicMainFragment;
    private MusicListFragment musicListFragment;
    private MusicSearchHistoryFragment musicSearchHistoryFragment;
    private MusicSearchFragment musicSearchFragment;
    private MusicDownLoadFragment musicDownLoadFragment;
    private MusicCollectFragment musicCollectFragment;
    private MusicRecentPlayFragment musicRecentPlayFragment;

    List<BillboardList> list=new ArrayList<>();
    List<BillboardList> listNew=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);
        list.clear();
        iMainPagePresenter=new IMainPagePresentImp(this);
        //遍历数组，请求各类榜单
        for (int t: type) {
        iMainPagePresenter.allBillboardList("billboard", t, 3, 0);
        }


        //获取榜单
        new Thread(new Runnable() {
            @Override
            public void run() {
            //new MainPageModel().billboardList("billboard", 1, 10, 0);//榜单
            //new MainPageModel().play(  "play", "523150864");//播放
            //new MainPageModel().search( "search", "卢冠廷");//搜索
            //new MainPageModel().lyrics( "lry", "877578");//获取歌词
            //new MainPageModel().singerInformation( "artist", "1100");//获取歌手信息
            //new MainPageModel().songLists( "songlist", "1100", 6);//获取推荐歌手列表
            //new MainPageModel().resultLists( "recommand", "290008", 10);//获取推荐列表
            }
        }).start();

        //接收事件，加载相应碎片
        RxBus.getDefault().register(MusicControlEvent.class).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<MusicControlEvent>() {
            @Override
            public void accept(MusicControlEvent event) throws Exception {
                if ((event.getTag())==30){//30：接收其他界面传递来的播放信息
                    if (playInterfaceFragment == null) {
                        playInterfaceFragment = new PlayInterfaceFragment();
                    } else {//主动释放引用
                        try {
                            playInterfaceFragment.getDialog().dismiss();
                            playInterfaceFragment = null;
                        } catch (Exception e) {
                            Log.e("---播放界面异常", e + "");
                            playInterfaceFragment = null;
                        }
                    }
                    if (playInterfaceFragment == null) {
                        playInterfaceFragment = new PlayInterfaceFragment();
                    }
                    Log.e("getFragmentManager()", getFragmentManager().toString());
                    //通过obj3作为类别判断
                    if (event.getObj3().equals("musicList")){//通过榜单播放
                        allSongs= (List<SongList>) event.getObj1();//通过榜单获得的音乐列表
                        Log.e("----音乐榜单音乐列表","allSongs:");
                        pos= (int) event.getObj2();
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("allSongs", (Serializable) event.getObj1());
                        bundle.putInt("pos", (int) event.getObj2());
                        playInterfaceFragment.setArguments(bundle);
                        playInterfaceFragment.show(getSupportFragmentManager(), "musicInterFace");
                    }if (event.getObj3().equals("musicSearch")){//通过搜索的音乐播放
                        singers= (List<Song>) event.getObj1();//通过历史搜索获得的音乐列表
                        Log.e("----历史搜索音乐榜单","singers:");
                        pos= (int) event.getObj2();
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("singers", (Serializable) event.getObj1());
                        bundle.putInt("pos", (int) event.getObj2());
                        playInterfaceFragment.setArguments(bundle);
                        playInterfaceFragment.show(getSupportFragmentManager(), "musicInterFace");
                    }
                }else if ((event.getTag())==31){//加载listMusicFragment
                    if (!FragmentUtil.isFragmentExist(getSupportFragmentManager(),"musicListFragment")){
                        musicListFragment=new MusicListFragment();
                        Bundle bundle = new Bundle();
                        bundle.putInt("type", (int) event.getObj1());
                        musicListFragment.setArguments(bundle);
                    }else {

                    }

                    FragmentUtil.showFragment(getSupportFragmentManager(),R.id.fl_fragments,musicListFragment,"musicListFragment",true);

                }else if ((event.getTag())==32){//隐藏listMusicFragment，加载musicMainFragment
                    //FragmentUtil.removeFragment(getSupportFragmentManager(),"musicListFragment");
                    FragmentUtil.popTopInclude(getSupportFragmentManager(),"musicListFragment");
                    /*if (getFragmentManager().findFragmentByTag("musicListFragment") != null) {//通过tag销毁输入源碎片
                        getFragmentManager().findFragmentByTag("musicListFragment").onDestroy();
                    }else {
                        getFragmentManager().findFragmentByTag("musicListFragment")=null;
                    }*/
                    //强制置为空
                    //musicListFragment=null;
                }else if ((event.getTag())==33){//加载musicDownLoadFragment
                    if (!FragmentUtil.isFragmentExist(getSupportFragmentManager(),"musicDownLoadFragment")){
                        musicDownLoadFragment=new MusicDownLoadFragment();
                    }
                    FragmentUtil.showFragment(getSupportFragmentManager(),R.id.fl_fragments,musicDownLoadFragment,"musicDownLoadFragment",true);
                }else if ((event.getTag())==34){//加载musicCollectFragment
                    if (!FragmentUtil.isFragmentExist(getSupportFragmentManager(),"musicCollectFragment")){
                        musicCollectFragment=new MusicCollectFragment();
                    }
                    FragmentUtil.showFragment(getSupportFragmentManager(),R.id.fl_fragments,musicCollectFragment,"musicCollectFragment",true);
                }else if (event.getTag()==35){//加载musicRecentPlayFragment
                    if (!FragmentUtil.isFragmentExist(getSupportFragmentManager(),"MusicRecentPlayFragment")){
                        musicRecentPlayFragment=new MusicRecentPlayFragment();
                    }
                    FragmentUtil.showFragment(getSupportFragmentManager(),R.id.fl_fragments,musicRecentPlayFragment,"musicRecentPlayFragment",true);
                }else if (event.getTag()==36){//关闭musicDownLoadFragment
                    FragmentUtil.popTopInclude(getSupportFragmentManager(),"musicDownLoadFragment");
                }else if (event.getTag()==37){//关闭musicCollectFragment
                    FragmentUtil.popTopInclude(getSupportFragmentManager(),"musicCollectFragment");
                }else if (event.getTag()==38){//关闭musicRecentPlayFragment
                    FragmentUtil.popTopInclude(getSupportFragmentManager(),"musicRecentPlayFragment");
                }else if ((event.getTag())==1000){//加载历史记录碎片
                    if (!FragmentUtil.isFragmentExist(getSupportFragmentManager(),"musicSearchHistoryFragment")){
                        musicSearchHistoryFragment=new MusicSearchHistoryFragment();
                        /*Bundle bundle = new Bundle();
                        bundle.putInt("type", (int) event.getObj1());
                        musicSearchHistoryFragment.setArguments(bundle);*/
                    }
                    FragmentUtil.showFragment(getSupportFragmentManager(),R.id.fl_fragments,musicSearchHistoryFragment,"musicSearchHistoryFragment",true);
                }else if ((event.getTag())==1001){//接收历史搜索返回来的字符串
                    //加载搜索的界面
                    if (!FragmentUtil.isFragmentExist(getSupportFragmentManager(),"musicSearchFragment")){
                        musicSearchFragment=new MusicSearchFragment();
                        Bundle bundle = new Bundle();
                        bundle.putString("searchText", (String) event.getObj1());
                        musicSearchFragment.setArguments(bundle);
                    }
                    FragmentUtil.showFragment(getSupportFragmentManager(),R.id.fl_fragments,musicSearchFragment,"musicSearchFragment",true);
                }else if ((event.getTag())==1002){//关闭搜索历史记录
                    FragmentUtil.popTopInclude(getSupportFragmentManager(),"musicSearchHistoryFragment");
                }else if ((event.getTag())==1003){//关闭搜索详情界面
                    FragmentUtil.popTopInclude(getSupportFragmentManager(),"musicSearchFragment");
                }else if ((event.getTag())==1004){//关闭播放界面
                    /*Log.e("----关闭播放界面","close");
                    //FragmentUtil.showFragment(getSupportFragmentManager(),0,playInterfaceFragment,"playInterfaceFragment");
                    //FragmentUtil.popTopInclude(getSupportFragmentManager(),"musicInterFace");
                    if (null!=playInterfaceFragment){

                    }*/
                }
            }
        });
        rlPlayCurrent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FragmentUtil.isFragmentExist(getSupportFragmentManager(),"musicInterFace")){
                    Log.e("----存在","存在");
                }else {
                    Log.e("----不存在","不存在");
                }
                RxBus.getDefault().post(new MusicControlEvent(1005,"显示正在播放的碎片"));
            }
        });



    }

    //点击两次退出
    /*long time = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {  //按键是否为返回键
            if (System.currentTimeMillis() - time > 2000) {
                Toast.makeText(getApplicationContext(), "双击退出", Toast.LENGTH_SHORT).show();
                time = System.currentTimeMillis();
                return true;
            }else{
                finish();
            }
            //return true;
        }
        return super.onKeyDown(keyCode, event);
    }*/
    @Override
    public void onBackPressed() {
        Intent setIntent = new Intent(Intent.ACTION_MAIN);
        setIntent.addCategory(Intent.CATEGORY_HOME);
        setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(setIntent);
    }

    //type	列表类型	1-新歌榜,2-热歌榜,11-摇滚榜,12-爵士,16-流行,21-欧美金曲榜,22-经典老歌榜,23-情歌对唱榜,24-影视金曲榜,25-网络歌曲榜
    @Override
    public void jumbMusicLIstDetail(BillboardList s) {
        list.add(s);
        if (list.size()==6){
            for (int i=0;i<list.size();i++){
                if (list.get(i).getLists()==null){//false：不为空（即断网,没数据） true:为空
                    bList=true;
                }else {
                    bList=false;
                    break;
                }
            }
            if (bList==true){
                return;
            }
            //处理数据
            dealData(list);
            //把请求后的数据传递到mainfragment
            Bundle bundle=new Bundle();
            bundle.putSerializable("mainData", (Serializable)list);
            //添加主页碎片

            if (null==musicMainFragment){
                musicMainFragment=new MusicMainFragment();
                musicMainFragment.setArguments(bundle);
            }
            FragmentUtil.showFragment(getSupportFragmentManager(),R.id.fl_fragments,musicMainFragment,"musicMainFragment",true);
        }
    }
    private void dealData(List<BillboardList> list) {
        if (bList==false) {
            for (BillboardList s : list) {
                if (s.getBillboard().getBillboard_type().equals("2")) {//热歌
                    if (null == allHotSongs) {
                        allHotSongs = new ArrayList<>();
                    }
                    if (allHotSongs.size() > 0) {
                        //allHotSongs.clear();
                    }
                    allHotSongs = s.getLists();
                    //对数据进行处理只取前面三个
                    if (null == hotSongs) {
                        hotSongs = new ArrayList<>();
                    }
                    if (hotSongs.size() > 0) {
                        hotSongs.clear();
                    }
                    for (int i = 0; i < 3; i++) {
                        hotSongs.add(s.getLists().get(i));
                    }
                    s.setLists(hotSongs);
                }
                if (s.getBillboard().getBillboard_type().equals("1")) {//新歌榜
                    if (null == allNewSongs) {
                        allNewSongs = new ArrayList<>();
                    }
                    if (allNewSongs.size() > 0) {
                        //allNewSongs.clear();
                    }
                    allNewSongs = s.getLists();
                    if (null == newSongs) {
                        newSongs = new ArrayList<>();
                    }
                    if (newSongs.size() > 0) {
                        newSongs.clear();
                    }
                    for (int i = 0; i < 3; i++) {
                        newSongs.add(s.getLists().get(i));
                    }
                    s.setLists(newSongs);
                }
                if (s.getBillboard().getBillboard_type().equals("22")) {//经典歌曲榜
                    if (null == allClassicalSongs) {
                        allClassicalSongs = new ArrayList<>();
                    }
                    if (allClassicalSongs.size() > 0) {
                        //allClassicalSongs.clear();
                    }
                    allClassicalSongs = s.getLists();
                    if (null == classicalSongs) {
                        classicalSongs = new ArrayList<>();
                    }
                    if (classicalSongs.size() > 0) {
                        classicalSongs.clear();
                    }
                    for (int i = 0; i < 3; i++) {
                        classicalSongs.add(s.getLists().get(i));
                    }
                    s.setLists(classicalSongs);
                }
                if (s.getBillboard().getBillboard_type().equals("21")) {//欧美金曲榜
                    if (null == allWesternSongs) {
                        allWesternSongs = new ArrayList<>();
                    }
                    if (allWesternSongs.size() > 0) {
                        //allWesternSongs.clear();
                    }
                    allWesternSongs = s.getLists();
                    if (null == westernSongs) {
                        westernSongs = new ArrayList<>();
                    }
                    if (westernSongs.size() > 0) {
                        westernSongs.clear();
                    }
                    for (int i = 0; i < 3; i++) {
                        westernSongs.add(s.getLists().get(i));
                    }
                    s.setLists(westernSongs);
                }
                if (s.getBillboard().getBillboard_type().equals("24")) {//影视金曲
                    if (null == allTeleplaySongs) {
                        allTeleplaySongs = new ArrayList<>();
                    }
                    if (allTeleplaySongs.size() > 0) {
                        //allTeleplaySongs.clear();
                    }
                    allTeleplaySongs = s.getLists();
                    if (null == teleplaySongs) {
                        teleplaySongs = new ArrayList<>();
                    }
                    if (teleplaySongs.size() > 0) {
                        teleplaySongs.clear();
                    }

                    for (int i = 0; i < 3; i++) {
                        teleplaySongs.add(s.getLists().get(i));
                    }
                    s.setLists(teleplaySongs);
                }
                if (s.getBillboard().getBillboard_type().equals("25")) {//网络歌曲
                    if (null == allNetworkSongs) {
                        allNetworkSongs = new ArrayList<>();
                    }
                    if (allNetworkSongs.size() > 0) {
                        //allNetworkSongs.clear();
                    }
                    allNetworkSongs = s.getLists();
                    if (null == networkSongs) {
                        networkSongs = new ArrayList<>();
                    }
                    if (networkSongs.size() > 0) {
                        networkSongs.clear();
                    }
                    for (int i = 0; i < 3; i++) {
                        networkSongs.add(s.getLists().get(i));
                    }
                    s.setLists(networkSongs);
                }

            }
        }
        //return listNew;
    }

    @Override
    public void jumb() {

    }

    @Override
    protected void onDestroy() {
        stopService(new Intent(this, CloudMusicService.class));
        super.onDestroy();
    }
}
